package com.zrrd.reggie.controller;

import com.zrrd.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

import static org.springframework.web.servlet.function.RequestPredicates.contentType;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
   @Value("${reggie.path}")
    private String baseUrl;
        @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
            log.info("我拿到图片了===》"+file.getOriginalFilename());
            log.info("文件位置=====>"+baseUrl);
            //获取原始名
            String originalFilename =file.getOriginalFilename();

            //获取文件后缀名

            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("文件后缀"+substring);
            String fileName = UUID.randomUUID().toString();
            fileName = fileName +substring;
            File f = new File(baseUrl);
            if (!f.exists()){
                f.mkdirs();
            }
          //记得写这里，还要改文件大小设置
            file.transferTo(new File(f,fileName));
            return R.success(fileName);
        }
        //文件下载
        @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
            File file =new File(baseUrl+name);
            if (file.exists()){
                try {
                    ServletOutputStream os = response.getOutputStream();
                    FileInputStream fis =new FileInputStream(file);
                    int len=0;
                    byte[] bytes =new byte[1024];
                    while((len=fis.read(bytes))!=-1){
                        os.write(bytes,0,len);
                        os.flush();
                    }
                    fis.close();
                    os.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
}
